import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { get_exam_list_async, get_subject_tree_async, get_topic_list_async, get_exam_topic_list_async, get_student_exam_topic_list_async } from './request'
import { initialState } from './data'
import { setExamListData, setSubjectTwoActive, setActiveTopic, setCurrentExamTopicId, setCorretExamTopicList, setCurrentSubjectTwo, setAnswerExamTopicList, setClearExamTopicList } from './action'

export const subjectSlice = createSlice({
  name: 'subject',
  initialState,
  reducers: {
    set_exam_list_data: setExamListData,
    set_subject_two_active: setSubjectTwoActive,
    set_active_topic: setActiveTopic,
    set_current_exam_topic_id: setCurrentExamTopicId,
    set_corret_exam_topic_list: setCorretExamTopicList,
    set_current_subject_two: setCurrentSubjectTwo,
    set_answer_exam_topic_list: setAnswerExamTopicList,
    set_clear_exam_topic_list: setClearExamTopicList
  },
  extraReducers: builder => {
    builder
      // 阅卷列表的数据
      .addCase(get_exam_list_async.pending, (state, res) => {
        state.loading = true
      })
      .addCase(get_exam_list_async.fulfilled, (state, res) => {
        state.exam_list_data.list = res.payload.data.data
        state.exam_list_data.count = res.payload.data.count
        state.loading = false
      })
      // 获取树型选择器中的课程
      .addCase(get_subject_tree_async.fulfilled, (state, res) => {
        state.subject_tree = res.payload
      })
      .addCase(get_topic_list_async.pending, (state, res) => {
        state.loading = true
      })
      // 获取题目列表
      .addCase(get_topic_list_async.fulfilled, (state, res) => {
        state.topic_list = res.payload
        state.loading = false
      })
      // 根据试卷ID获取题目列表
      .addCase(get_exam_topic_list_async.fulfilled, (state, res) => {
        // console.log(res.payload)
        state.exam_topic_list = res.payload.exam
        state.current_exam_topic_id = res.payload.exam[0]._id
        state.current_exam_score = res.payload.score
      })
      // 学生获取试卷题目
      .addCase(get_student_exam_topic_list_async.fulfilled, (state, res) => {
        state.exam_topic_list = res.payload
        // 因为进去要默认显示第一个，所以获取第一个题目的id
        state.current_exam_topic_id = res.payload[0]?._id
      })
  }
})

export const { set_exam_list_data, set_subject_two_active, set_active_topic, set_current_exam_topic_id, set_corret_exam_topic_list, set_current_subject_two, set_answer_exam_topic_list, set_clear_exam_topic_list } = subjectSlice.actions

export default subjectSlice.reducer
